require 'Object'
require 'Utility'

class Turret < MovableObject
  
  attr_accessor :turn_force, :move_force, :components
  
  def initialize(x,y)
    @components = []
    
    @turn_speed = 15
    @health = 100
    
    @targeting_range = 200 # searches for targets in this range
    @target = nil
    
    shape = BaseShapes::Box
    super(Images[:turret_base], shape, true)
    
    @shape.collision_type = :turret
    @gun = Images[:turret_gun]
    @gun_angle = 0 
    
    @weapon = $component_catalogue['wep-builtin-blaster'].clone
    @weapon.add_to self, 1
    
    warp(vect(x,y))
        
  end
  
  def draw
    super
    
    v = $game.camera.adjusted_coords(@x,@y)
    @gun.draw_rot(v.x, v.y, @zindex, @gun_angle)
    
    
#    $game.draw_line(v.x, v.y, 0xffffffff, look_point.x, look_point.y, 0xffffffff,100)
    
  end
  
  def acquire_target
    objs = objects_within_range(@body.p, @targeting_range)
    @target = objs.first
    log 'Acquired target ' + @target.to_s
  end
  
  def update
    
    # if we have no target, acquire one
    if not @target then
      acquire_target
    end
    
    if (@target) then
      # make the turret turn towards the target

      target_pos = @target.body.p
      
      angle = target_pos - @body.p
      
      angle = Math::atan2(angle.y, angle.x);
      
      angle = angle.radians_to_gosu
          
      turn_direction =  @gun_angle - angle
      
      turn_direction = turn_direction % 360
      turn_direction += 360 if turn_direction < 0
      
      if turn_direction < 180 then
        @gun_angle -= @turn_speed * $dt
      else
        @gun_angle += @turn_speed * $dt
      end
      
      @weapon.fire
    end
    @weapon.update
  
    super
    
  end
  
  def aim_angle
    @gun_angle.gosu_to_radians
  end
  
  def destroyed_object(object)
    puts 'Turret ' + to_s + ' destroyed ' + object.to_s + '!'
    @target = nil
  end
  
  def destroy
    explode
    super
  end
  
end